#include <vector>
using namespace std;
struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};
/*
 * @lc app=leetcode.cn id=129 lang=cpp
 *
 * [129] 求根节点到叶节点数字之和
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:

    // int res = 0;
    // int sumNumbers(TreeNode* root) {
    //     helper(root, 0);
    //     return res;
    // }

    // void helper(TreeNode* root, int now) {
    //     if (!root) return;
    //     int x = now * 10 + root->val;
    //     if (!root->left && !root->right) {
    //         res += x; return;
    //     }
    //     helper(root->left, x);
    //     helper(root->right, x);
    //     return;
    // }

    int sumNumbers(TreeNode* root) {
        return dfs(root, 0);
    }

    int dfs(TreeNode* root, int now) {
        if (!root) return 0;
        int x = now * 10 + root->val;
        if (!root->left && !root->right) {
            return x;
        } else {
            return dfs(root->left, x) + dfs(root->right, x);
        }
    }
    
};
// @lc code=end

